package query_service

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math/rand"
	"mine-info-server/app/convertor"
	"mine-info-server/domain/common-context/query"
	"mine-info-server/domain/common-context/repo"
	"mine-info-server/global"
	"mine-info-server/interfaces/response"
	"mine-info-server/utils"
	"strconv"
)

/*
   @author:zhongyang
   @date:2023/4/11
   @description:通用-查询应用服务
*/

type CommonQueryService struct {
	MsgRepo      repo.MsgIRepo
	BlessingRepo repo.BlessingWordIRepo
	convertor    convertor.CommonConvertor
}

func NewCommonQueryService() *CommonQueryService {
	return &CommonQueryService{}
}

func (s *CommonQueryService) GetUserInfo() (map[string]string, error) {
	// 调用仓储层获取用户信息聚合根
	adminUser := map[string]string{
		"email":     "coderzy@foxmail.com",
		"nick_name": "Batman",
	}
	return adminUser, nil
}

func (s *CommonQueryService) GetOnlineUserTotal(c *gin.Context) (int64, error) {
	// 缓存中取数，直接应用层拿就可以了
	result, err := global.GVA_REDIS.ZCard(c, "online_users").Result()
	if err != nil {
		// 这里不返回错误，直接显示0就行
		global.GVA_LOG.Error("AdminUserService.GetOnlineUserTotal err:", zap.Error(err))
		return 0, nil
	}
	return result, nil
}

func (s *CommonQueryService) IsMsgAllRead(c *gin.Context) (bool, error) {
	userID := utils.GetUserID(c)
	return s.MsgRepo.IsMsgAllRead(userID)
}

func (s *CommonQueryService) GetMsgList(c *gin.Context, query *query.GetMsgListQuery) ([]*response.MsgItemResponse, int64, error) {
	userID := utils.GetUserID(c)
	return s.MsgRepo.GetMsgPageByUserId(query.Page, userID, query.PageSize, query.IsRead)
}

func (s *CommonQueryService) GetBlessingWord() (*response.BlessingWordResponse, error) {
	maxId, err := s.BlessingRepo.GetMaxId()
	if err != nil {
		return nil, err
	}
	wordId := rand.Intn(maxId) + 1
	res, err := s.BlessingRepo.GetBlessingWordById(strconv.Itoa(wordId))
	if err != nil {
		return nil, err
	}
	return s.convertor.ConvertBlessingWordResponse(res), nil
}
